# *****************************************************************
# OVERVIEW ####
# *****************************************************************
# REGRESSION_SI.R
# Are Rural Attitudes Just Republican?
# Core Functions for Data Analysis
# Jennifer Lin and Kristin Lunz Trujillo
# Created On: 2023 01 27

# *** The code in this file replicates the regression analyses in
#   the paper and includes code on components that are in the 
#   Supplemental Appendix. ***

# ** Before running this file, ensure that you have ran
#   - Functions.R
#   - ANES20_CLEAN.R
#  or components of this code will result in an error. See 
#  00_GENERAL.R for more details **

# *****************************************************************
# INFERENTIAL STATISTICS IN SUPPLEMENTAL APPENDIX ####
# *****************************************************************

# The following code generates the tables and figures that are 
#   present in the Supplemental Appendix.

# To start, we extract the variables that we want to regress. As
#   mentioned in the paper, the selection of variables is based on
#   significant differences within each party by urban-rural 
#   factors. This leads to the following variables:
vars_to_regress <- ANES_Issues %>%
  select(starts_with("I_"))

# To run the regression using survey weights, we declare the data
#   as a survey object and remove Independents
ANES_regress_Data <- ANES_Issues %>%
  filter(PARTY != "Independent") %>%
  srvyr::as_survey(weight = V200010a)

# We iterate through each of the variables and apply the model 
#   specified in the paper and in the `issues_model_si()` 
#   function.
I_results <- issues_model_SI(
  vars_to_regress, 1:22, design = ANES_regress_Data)

# Create a vector of terms to label predictors in the models to 
#   use with the regression table exports.
terms <- c(
  "Rural Resident",
  "Republican",
  "Trump Supporter",
  "Ideology",
  "Female",
  "Income",
  "Education",
  "Age",
  "Racial Resentment -- Work without Favors",
  "Racial Resentment -- History of Slavery",
  "Racial Resentment -- Blacks get less",
  "Racial Resentment -- Try Harder",
  "Racial Minority",
  "Church",
  "Rural Resident X Republican"
)

# We can plot the results in a graph, as shown in Supplemental
#   Appendix E.

# To start, create an empty list to store results from each of the
#   regression models
plot_df <- list()

# To get the estimates and standard erros to plot, we pull these#
#   details from our list of regression models, iterating
#   trhough each model one by one
for (i in 1:length(I_results)) {
  plot_df[[i]] <- tidy(I_results[[i]])
  plot_df[[i]]$variable <- names(vars_to_regress[i])
}

# We then clean up the resulting data frame, renaming the 
#   varaible names as needed
plot_df_clean <- bind_rows(plot_df) %>% 
  filter(term %in% c(
    "RURALTRUE", "PARTYRepublican", "RURALTRUE:PARTYRepublican")) %>% 
  mutate(
    Issue_Desc = case_when(
      variable == "I_refugees" ~ "Allow Refugees to Come to US",
      variable == "I_citizenship" ~ "Provide a Path to Citizenship",
      variable == "I_deport" ~ "Deporting Immigrants to Native Country",
      variable == "I_SPChild" ~ "Separating Children from Parents at Border",
      variable == "I_reduceIneq" ~ "Reduce Income Inequality",
      variable == "I_ACA" ~ "Approve Affordable Care Act",
      variable == "I_reqVax" ~ "Require Vaccinations",
      variable == "I_RegGHG" ~ "Regulate Greenhouse Gas Emissions",
      variable == "I_bkgCheck" ~ "Background Check for Gun Purchases",
      variable == "I_banAR" ~ "Ban Assault Style Rifles",
      variable == "I_buyBackAR" ~ "Assault Rifle Buy Back",
      variable == "I_Opioid" ~ 'Address Opioid Epidemic',
      variable == "I_FreeTrade" ~ "Allowing Free Trade Agreements",
      variable == "I_UBI" ~ "Provide Citizens 12K A Year",
      variable == "I_incHCspend" ~ "Increasing Spending to Cover Health Care",
      variable == "I_TransMil" ~ "Allow Transgender People to Serve in Military",
      variable == "I_ReqIDVote" ~ "Require ID to Vote",
      variable == "I_FelonVote" ~ "Allowing Felons to Vote",
      variable == "I_JAccess" ~ "Transparency for Journalists",
      variable == "I_FamilyLeave" ~ "Provide Paid Family Leave",
      variable == "I_birthright" ~ "End Birthright Citizenship",
      variable == "I_BorderWall" ~ "Build Wall on Southern Border"
    ),
    Issue_Desc = factor(Issue_Desc, levels = unique(Issue_Desc)),
    term = case_when(
      term == "RURALTRUE" ~ "Rural Resident",
      term == "PARTYRepublican" ~ "Republican",
      term == "RURALTRUE:PARTYRepublican" ~ "Rural X Republican"
    ),
    term = factor(
      term,
      levels = c(
        "Rural Resident", "Republican", "Rural X Republican"
      )
    )
  )

# Finally, we generate the plot
ggplot(plot_df_clean, aes(x = term, y = estimate))+
  geom_pointrange(
    aes(
      ymin = estimate-1.96*std.error, 
      ymax = estimate+1.96*std.error)
  )+
  geom_hline(
    yintercept = 0, 
    color = "grey75", linetype = "dashed")+
  facet_wrap(~Issue_Desc, ncol = 2)+
  coord_flip()+
  labs(
    title = "Favor or Oppose?",
    subtitle = 
      "Evaluations of Core Issues by Place of Residence and Party",
    caption = 
      "Data: American National Elections Studies (ANES) 2020"
  )+
  ylab("Estimate")+
  xlab("Key Predictors")+
  theme_bw()+
  theme(
    plot.title    = element_text
    (hjust = 0.5, size = 20, colour="black", face = "bold"),
    plot.subtitle = element_text(
      hjust = 0.5, size = 16, colour="black"),
    legend.title  = element_text
    (hjust = 0.5, size = 14, colour="black", face = "bold"),
    plot.caption  = element_text(
      size = 10, colour="black"),
    axis.title    = element_text(
      size = 14, colour="black"),
    axis.text.x   = element_text(
      size = 12, colour="black", angle = 0, hjust = 0.5)
  )  

# *****************************************************************
# CHECK SUBURB AND CITY DIFFERENCES ####
# *****************************************************************

# We can run a regression model using the model predefined
#   in the Functions.R file called "SC_model".
I_results <- SC_model(
  vars_to_regress, 1:22, design = ANES_regress_Data)

# Then, we can generate a plot that appears in the page.

# To start, create an empty list to store results from each of the
#   regression models
plot_df <- list()

# To get the estimates and standard erros to plot, we pull these#
#   details from our list of regression models, iterating
#   trhough each model one by one
for (i in 1:length(I_results)) {
  plot_df[[i]] <- tidy(I_results[[i]])
  plot_df[[i]]$variable <- names(vars_to_regress[i])
}

# We then clean up the resulting data frame, renaming the 
#   varaible names as needed
plot_df_clean <- bind_rows(plot_df) %>% 
  filter(grepl("Place_Party", term)) %>% 
  mutate(
    Issue_Desc = case_when(
      variable == "I_refugees" ~ "Allow Refugees to Come to US",
      variable == "I_citizenship" ~ "Provide a Path to Citizenship",
      variable == "I_deport" ~ "Deporting Immigrants to Native Country",
      variable == "I_SPChild" ~ "Separating Children from Parents at Border",
      variable == "I_reduceIneq" ~ "Reduce Income Inequality",
      variable == "I_ACA" ~ "Approve Affordable Care Act",
      variable == "I_reqVax" ~ "Require Vaccinations",
      variable == "I_RegGHG" ~ "Regulate Greenhouse Gas Emissions",
      variable == "I_bkgCheck" ~ "Background Check for Gun Purchases",
      variable == "I_banAR" ~ "Ban Assault Style Rifles",
      variable == "I_buyBackAR" ~ "Assault Rifle Buy Back",
      variable == "I_Opioid" ~ 'Address Opioid Epidemic',
      variable == "I_FreeTrade" ~ "Allowing Free Trade Agreements",
      variable == "I_UBI" ~ "Provide Citizens 12K A Year",
      variable == "I_incHCspend" ~ "Increasing Spending to Cover Health Care",
      variable == "I_TransMil" ~ "Allow Transgender People to Serve in Military",
      variable == "I_ReqIDVote" ~ "Require ID to Vote",
      variable == "I_FelonVote" ~ "Allowing Felons to Vote",
      variable == "I_JAccess" ~ "Transparency for Journalists",
      variable == "I_FamilyLeave" ~ "Provide Paid Family Leave",
      variable == "I_birthright" ~ "End Birthright Citizenship",
      variable == "I_BorderWall" ~ "Build Wall on Southern Border"
    ),
    Issue_Desc = factor(Issue_Desc, levels = unique(Issue_Desc)),
    term = case_when(
      term == "Place_PartyDemocrat - Suburb" ~ "Democrat - Suburb",
      term == "Place_PartyDemocrat - Small Town" ~ "Democrat - Small Town",
      term == "Place_PartyDemocrat - Rural Area" ~ "Democrat - Rural Area",
      term == "Place_PartyRepublican - City" ~ "Republican - City",
      term == "Place_PartyRepublican - Suburb" ~ "Republican - Suburb",
      term == "Place_PartyRepublican - Small Town" ~ "Republican - Small Town",
      term == "Place_PartyRepublican - Rural Area" ~ "Republican - Rural Area"
    ),
    term = factor(
      term,
      levels = c(
        "Democrat - Suburb", "Democrat - Small Town", "Democrat - Rural Area",
        "Republican - City", "Republican - Suburb", "Republican - Small Town",
        "Republican - Rural Area"
      )
    )
  ) %>% 
  filter(grepl("Suburb|City", term))

# Finally, we generate the plot
ggplot(plot_df_clean, aes(x = term, y = estimate))+
  geom_pointrange(
    aes(ymin = estimate-1.96*std.error, ymax = estimate+1.96*std.error)
  )+
  geom_hline(yintercept = 0, color = "grey75", linetype = "dashed")+
  facet_wrap(~Issue_Desc, ncol = 2)+
  coord_flip()+
  labs(
    title = "Favor or Oppose?",
    subtitle = "Evaluations of Core Issues by Place of Residence and Party",
    caption = "Data: American National Elections Studies (ANES) 2020"
  )+
  ylab("Estimate")+
  xlab("Key Predictors")+
  theme_bw()+
  theme(
    plot.title    = element_text(hjust = 0.5, size = 20, colour="black", face = "bold"),
    plot.subtitle = element_text(hjust = 0.5, size = 16, colour="black"),
    legend.title  = element_text(hjust = 0.5, size = 14, colour="black", face = "bold"),
    plot.caption  = element_text(size = 10, colour="black"),
    axis.title    = element_text(size = 14, colour="black"),
    axis.text.x   = element_text(size = 12, colour="black", angle = 0, hjust = 0.5)
  ) 
